package com.gujiangbo.juc;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Author: gujiangbo.co
 * @Contact: 646832012@qq.com
 * @Date: 2022/6/13 12:46
 * @Version: 1.0
 * @Description:
 */
public class SafeDoubleCheckSingleton {
    private static volatile SafeDoubleCheckSingleton singleton;

    private SafeDoubleCheckSingleton() {
    }

    public static SafeDoubleCheckSingleton getInstance() {
        if (singleton == null) {
            synchronized (SafeDoubleCheckSingleton.class) {
                if (singleton == null) {
                    singleton = new SafeDoubleCheckSingleton();
                }
            }
        }
        return singleton;
    }

    public static void main(String[] args) {
        Set<SafeDoubleCheckSingleton> set = new HashSet<>();
        // 创建N个线程
        for (int i = 1; i <= 10; i++) {
            new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    set.add(SafeDoubleCheckSingleton.getInstance());
                    System.out.println(Thread.currentThread().getName() + "--->" + j);
                }
            }, String.valueOf(i)).start();
        }
        //暂停10秒钟线程
        while (true) {
            if (Thread.activeCount() == 2) {
                System.out.println(set.size());
                break;
            }
        }
    }
}
